package com.example.java_gobang.API;

import com.example.java_gobang.mapper.UserMapper;
import com.example.java_gobang.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LXW
 * Date: 2022-08-03
 * Time: 18:31
 */
@RestController
public class UserAPI {
    @Autowired
    private UserMapper userMapper;

    /**
     * 实现登录请求
     * @param username
     * @param password
     * @param request
     * @return
     */
    @RequestMapping("/login")
    public Object login(String username, String password, HttpServletRequest request) {
        // 去数据库中查询user
        User user = userMapper.selectByName(username);
        if(user == null || !user.getPassword().equals(password)) {
            // 登录失败
            System.out.println("登陆失败");
            return new User();
        }
        // 将user对象存入会话中
        HttpSession session = request.getSession(true);
        session.setAttribute("user", user);
        return user;
    }

    /**
     * 实现注册请求
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/register")
    public Object register(String username, String password) {
        try{
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            // 将user对象存入数据库中
            userMapper.insert(user);
            return user;
        }catch (org.springframework.dao.DuplicateKeyException e) {
            return new User();
        }
    }

    /**
     * 实现查询用户信息请求
     * @param request
     * @return
     */
    @RequestMapping("/userInfo")
    public Object getUserInfo(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute("user");
            User newUser = userMapper.selectByName(user.getUsername());
            return newUser;
        }catch (NullPointerException e) {
            return  new User();
        }
    }
}
